package com.example.shellshopping.goods;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.shellshopping.R;
import com.example.shellshopping.login.PersonCenterMainActivity;
import com.example.shellshopping.login.UserBean;
import com.example.shellshopping.personCenter.PersonSettingRepwdActivity;
import com.example.shellshopping.utils.BaseActivity;
import com.example.shellshopping.utils.BuyNumDialog;
import com.example.shellshopping.utils.SaveUserUtils;
import com.example.shellshopping.utils.URLUtils;
import com.google.gson.Gson;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;

import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class GoodsDetailsActivity extends BaseActivity {
    TextView tv1,tv2,tv3,tv4,tv5;
    ImageView iv,backIV,shoppingcarIv;
    GridView likegv;
    GoodsBean.DataBean dataBean;
    GoodsDetailsBean.DataBean dataDetailBean;
    List<GoodsBean.DataBean> data;
    LikeTypeAdapter adapter;
    boolean islogin = false;
    private Bitmap Bitmap;
    private UserBean.DataBean userInfo; //之前登录时保存的用户信息

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_goods_details);
        userInfo = SaveUserUtils.getUserInfo(this);  //获取登录时保存的用户信息
        islogin = isLogin();
        initView();
        setListener();
        dataDetailBean = (GoodsDetailsBean.DataBean) getIntent().getSerializableExtra("goods");  //（替换方法）接收数据
        changePage();  //更具点击页面，更改页面信息
        setViewContext();  //设置猜你喜欢
        //数据源
        data = new ArrayList<>();
        //适配器
        adapter = new LikeTypeAdapter(this, data);
        likegv.setAdapter(adapter);
        //联网
        getNetwork(URLUtils.guessYouLike_url);
    }

    private void setListener() {
        tv4.setOnClickListener(onClickListener);
        tv5.setOnClickListener(onClickListener);
        backIV.setOnClickListener(onClickListener);
    }

    View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int id = v.getId();
            String msg;
            switch (id) {
                case  R.id.activity_goods_detail_car_tv:
                    msg = "添加购物车之前请先登录";
                    showBuyDialog(msg,2);
                    break;
                case R.id.activity_goods_detail_buy_tv:
                    msg = "购买之前请先登录";
                    showBuyDialog(msg,1);
                    break;
                case R.id.activity_goods_back:
                    finish();
                    break;
                case R.id.activity_goods_detail_shopping_car_tv:
                    jumpToShoppingCar();  //进入购物车
                    break;
            }
        }
    };

    //进入购物车
    private void jumpToShoppingCar() {
        finish();
        Intent intent = new Intent(this, GoodsShoppingCarActivity.class);
        startActivity(intent);
    }

    private void showBuyDialog(String msg,int flag) {
        if (islogin) {  //登录
            BuyNumDialog dialog = new BuyNumDialog(GoodsDetailsActivity.this);
            dialog.show();
            dialog.setStorage_num(dataDetailBean.getCount());//设置库存
            dialog.setDialogWidth();
            dialog.setOnEnsureListener(new BuyNumDialog.OnEnsureListener() {
                @Override
                public void onEnsure(int num) {
                    if (flag == 1) {//购买按钮进入
                        //跳转到支付页面，传数据————商品id(通过dataDetailBean直接获得)和购买数量

                    }else if(flag ==2){//购物车按钮进入
                        //添加购物车
                        addShoppingCar(num);
                    }
                    dialog.cancel();
                }
            });

        }else{  //未登录
            Toast.makeText(GoodsDetailsActivity.this,msg,Toast.LENGTH_SHORT).show();
        }
    }

    //添加购物车
    private void addShoppingCar(int num) {
        Map<String,String> map = new HashMap<>();
        map.put("userId",String.valueOf(userInfo.getId()));
        map.put("commodityId",String.valueOf(dataDetailBean.getId()));
        map.put("count",String.valueOf(num));
        //post网络请求
        String url = URLUtils.insertShoppingCar;
        RequestParams params = new RequestParams(url);
        //将提交的键值对放到请求参数当中
        Set<String> keySet = map.keySet();
        for(String key:keySet){
            String val = map.get(key);
            params.addParameter(key,val);
        }
        params.setAsJsonContent(true);
        params.setBodyContentType("application/json;charset=utf-8");
        x.http().post(params, new CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Toast.makeText(GoodsDetailsActivity.this,"添加购物车成功",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }


    //判断是否登录，如果登录就跳转到个人中心页面
    private boolean isLogin() {
        UserBean.DataBean userInfo = SaveUserUtils.getUserInfo(this);
        if(userInfo==null)
            return false;
        return true;
    }

    @Override
    public void onSuccess(String result){
        super.onSuccess(result);
        //Toast.makeText( getContext(), "查询成功", Toast.LENGTH_SHORT ).show();
        GoodsBean goodsBean = new Gson().fromJson(result,GoodsBean.class);//解析数据
        List<GoodsBean.DataBean> list = goodsBean.getData();//获取网络集合
        data.addAll(list);//将网络数据添加到list view的数据源当中
        adapter.notifyDataSetChanged();//提示更新
    }

    private void setViewContext() {

    }

    private void changePage() {
        tv1.setText(String.valueOf(dataDetailBean.getPrice()));
        tv2.setText(dataDetailBean.getName());
        tv3.setText(dataDetailBean.getInfo());
        String str = dataDetailBean.getPhoto();
        if (!TextUtils.isEmpty(str)) {
            String photourl = URLUtils.PUBLIC_URL+str;
            Picasso.with(this).load(photourl).into(new Target() {
                @Override
                public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                    Bitmap = bitmap;
                }

                @Override
                public void onBitmapFailed(Drawable errorDrawable) {

                }

                @Override
                public void onPrepareLoad(Drawable placeHolderDrawable) {

                }
            });
            iv.setBackground(new BitmapDrawable(getResources(),Bitmap));
        }
    }

    private void initView() {
        tv1 = findViewById(R.id.activity_goods_detail_price_tv);
        tv2 = findViewById(R.id.activity_goods_detail_tile_tv);
        tv3 = findViewById(R.id.activity_goods_detail_introduce_tv);
        tv4 = findViewById(R.id.activity_goods_detail_car_tv);
        tv5 = findViewById(R.id.activity_goods_detail_buy_tv);
        iv = findViewById(R.id.activity_goods_detail_photo_tv);
        likegv = findViewById(R.id.details_gv);
        backIV = findViewById(R.id.activity_goods_back);
        shoppingcarIv = findViewById(R.id.activity_goods_detail_shopping_car_tv);
    }
}